class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

head=ListNode(-10)
head.next=(-3)
head.next.next=ListNode(0)
head.next.next.next=ListNode(5)
head.next.next.next.next=ListNode(9)

def dfs(nums,left,right):
    if left>right:
        return None
    #取中间位置mid
    mid=(left+right)>>1
    #根节点构建
    # print("nums[mid]:",nums[mid])
    root=TreeNode(nums[mid])
    # print(nums[left:mid-1])
    #左子树构建
    root.left=dfs(nums,left,mid-1)
    #右子树构建
    # print(nums[mid+1:right])
    root.right=dfs(nums,mid+1,right)
    return root

def sortedListToBST(head):
    nums=[]
    while head:
        nums.append(head.val)
        head=head.next
    return dfs(nums,0,len(nums)-1)
sortedListToBST(head)